<?php

namespace app\adminapi\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use app\model\PlatformConfigModel;

class AliCloud extends BaseAdminApi
{
    //调用STS服务AssumeRole
    public function getAuth()
    {
        // 从数据库获取阿里云OSS配置
        $ossConfig = PlatformConfigModel::getConfig('aliyun_oss');

        if (!$ossConfig) {
            return $this->fail('阿里云OSS配置不存在，请先在后台配置');
        }

        $alyunConfig = [
            'accessKeyId' => $ossConfig['accessKeyId'],
            'accessKeySecret' => $ossConfig['accessKeySecret'],
            'regionId' => $ossConfig['regionId'],
            'RoleArn' => $ossConfig['RoleArn'],
            'RoleSessionName' => $ossConfig['RoleSessionName']
        ];

        // 验证必要的配置项
        if (empty($alyunConfig['accessKeyId']) || empty($alyunConfig['accessKeySecret']) || empty($alyunConfig['RoleArn'])) {
            return $this->fail('阿里云OSS配置不完整，请检查AccessKeyId、AccessKeySecret和RoleArn配置');
        }

        //构建一个阿里云客户端，用于发起请求。
        //设置调用者（RAM用户或RAM角色）的AccessKey ID和AccessKey Secret。
        AlibabaCloud::accessKeyClient($alyunConfig["accessKeyId"], $alyunConfig["accessKeySecret"])
            ->regionId($alyunConfig["regionId"])
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Sts')
                ->scheme('https') // https | http
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => $alyunConfig["regionId"],
                        'RoleArn' => $alyunConfig["RoleArn"],
                        'RoleSessionName' => $alyunConfig["RoleSessionName"],
                    ],
                ])
                ->request();

            return $this->success($result->toArray());
        } catch (ClientException $e) {
            return $this->fail($e->getErrorMessage());
        }
    }
}
